package com.krediti.session;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

import com.krediti.entity.Korisnik;

@Name("authenticator")
public class Authenticator {
	@Logger
	Log log;

	@In
	Identity identity;

	@In
	EntityManager entityManager;

	@Out(value = "ulogovaniKorisnik", scope = ScopeType.SESSION, required = false)
	Korisnik korisnik;
	String ime;
	
	boolean isUser = false;

	public boolean isUser() {
		return isUser;
	}

	public void setUser(boolean isUser) {
		this.isUser = isUser;
	}

	/**
	 * Examines username and passwords.
	 * 
	 * @return true if user can login, false otherwise.
	 */

	public boolean authenticate() {
		log.info("authenticating #0", identity.getUsername());
	//	identity.setPassword("tanjav");
		checkUser(identity.getUsername(), identity.getPassword());
		
		if (isUser()) {
			identity.addRole("admin");
			return true;
		} else{
			return false;
		}

	}

	/**
	 * Check if there is the user in the table KORISNIK to login.
	 * 
	 * @param username
	 *            String
	 * @param password
	 *            String
	 * @return true if user exists, false if user does not exists.
	 */
	private void checkUser(String username, String password) {
		if(entityManager!=null)
			try {
				korisnik = (Korisnik) entityManager
						.createQuery(
								"from Korisnik where username = :username and password = :password")
						.setParameter("username", username).setParameter(
								"password", password).getSingleResult();
				
				if (korisnik != null && korisnik.getId() != null) 
					setUser(true);
				
			} catch (NoResultException ex) {
                
			}
			
		
	}

}
